import { readFileSync } from 'fs';
import { defineConfig } from 'rollup';
import resolve, { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from '@rollup/plugin-typescript';
import url from '@rollup/plugin-url';
import terser from '@rollup/plugin-terser';

import json from '@rollup/plugin-json';
import svgr from '@svgr/rollup';

import external from 'rollup-plugin-peer-deps-external';
import postcss from 'rollup-plugin-postcss';
// import dts from 'rollup-plugin-dts';
import typescriptEngine from 'typescript';
import _ from 'lodash';

const packageJson = JSON.parse(readFileSync('./package.json'));
export const custonComponentsList = [
  {
    ccKey: 'a21cc41c-ebf8-4c0e-aa65-3d7d6e84feb3',
    ccSecret: '53C8B53264D4557431B320FCCE367A180EAFBC1F2B81A35698E9FBE5096E6BEFDF0236431C0491BC44139D3A8C986089',
  },
];

let defaultConfig = {
  input: './src/index.ts',
  output: [
    {
      name: 'customComponent',
      file: packageJson.module,
      format: 'umd',
      exports: 'named',
      sourcemap: false,
      globals: {
        react: 'React',
        'react/jsx-runtime': 'jsxRuntime',
        '@ant-design/icons': 'icons',
        '@ant-design/charts': 'charts',
        antd: 'antd',
        axios: 'axios',
        dayjs: 'dayjs',
      },
    },
  ],
  plugins: [
    external({ includeDependencies: true }),
    resolve(),
    commonjs(),
    svgr(),
    url(),
    json(),
    postcss({
      plugins: [],
      minimize: true,
    }),

    typescript({
      tsconfig: './tsconfig.json',
      typescript: typescriptEngine,
      sourceMap: true,
      exclude: [
        'coverage',
        '.storybook',
        'storybook-static',
        'config',
        'dist',
        'node_modules/**',
        '*.cjs',
        '*.mjs',
        '**/__snapshots__/*',
        '**/.storybook/*',
        '**/__tests__',
        '**/*.test.js+(|x)',
        '**/*.test.ts+(|x)',
        '**/*.mdx',
        '**/*.story.ts+(|x)',
        '**/*.story.js+(|x)',
        '**/*.stories.ts+(|x)',
        '**/*.stories.js+(|x)',
        'setupTests.ts',
        'vite.config.ts',
        'vitest.config.ts',
      ],
    }),
    terser(),
  ],
  external: [
    'antd',
    'lodash',
    'react',
    'react/jsx-runtime',
    'react-dom',
    '@ant-design/icons',
    'axios',
    '@ant-design/charts',
    // 'mathjs',
    'dayjs',
    // 'valtio',
    // 'nanoid',
    /\.mjs$/,
  ],
};

export default defineConfig(
  custonComponentsList.map((cc) => {
    let cfg = _.cloneDeep(defaultConfig);
    cfg.input = `./src/index.${cc.ccKey.split('-')[0]}.ts`;
    cfg.output[0].file = `dist/index.${cc.ccKey.split('-')[0]}.js`;
    return cfg;
  }),
);
